package com.cpi.cornpp.version.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.version.exception.VersionException;
import com.cpi.cornpp.version.form.VersionForm;
import com.cpi.cornpp.version.services.VersionService;
import com.cpi.cornpp.version.view.VersionView;

public class SaveNewVersionAction extends Action {
	private final static String CUSTOM_EXCEPTION = "custom_exception";//$NON-NLS-1$
	private static final String SUCCESS_FORWARD = "toSuccess";
	private static final String FAILURE_FORWARD = "error";
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws VersionException{
		VersionForm versionForm = null;
		VersionView versionView = null;
		VersionView versionFormView = null;
		VersionService versionService = null;
		HttpSession session = null;
		ActionForward forward = null;
		
		forward = mapping.findForward(FAILURE_FORWARD);
		session = request.getSession(false);
		
		try{
			
			if (form != null){
				versionView = new VersionView();
				versionService = new VersionService();
				versionForm = (VersionForm) form;
				versionFormView = versionForm.getVersionView();
				
				if (versionFormView != null){
					versionView.setParentId(versionFormView.getParentId());
					versionView.setShortName(versionFormView.getShortName());
					versionView.setDescription(versionFormView.getDescription());
					versionView.setStartDate(versionFormView.getStartDate());
					versionView.setEndDate(versionFormView.getEndDate());
					versionView.setRelatedType(versionFormView.getRelatedType());
					versionView.setActive(true);
					
					versionService.addVersion(versionView);
					
					forward = mapping.findForward(SUCCESS_FORWARD);
				}
			}
			
		} catch (VersionException versionException){
			session.setAttribute(CUSTOM_EXCEPTION, versionException);
			throw versionException;
		} catch (Exception e){
			VersionException versionException=null;
			e.printStackTrace(System.out);
			versionException= new VersionException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_LISTS);
			session.setAttribute(CUSTOM_EXCEPTION, versionException);
			throw versionException;
		}
		
		return forward;
	}
}